<?php

namespace App\Admin\Actions\Coupon;

use App\Models\yb\GoodsModel;
use App\Models\yb\SmsModel;
use App\Models\yb\UserModel;
use Encore\Admin\Actions\BatchAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Cisco\Aliyunsms\Facades\Aliyunsms;


class Remind extends BatchAction
{
    protected $selector = '.remind';

    public function handle(Collection $collection, Request $request)
    {
        $sms_code = $request->post('sms_code');

        try {
            $phone = array();
            foreach ($collection as $model) {
                $user_id = $model['user_id'];
                $user_data = UserModel::where(['id'=>$user_id])->select('phone')->first();
                $phone[] = $user_data['phone'];
            }
            $phone = array_unique($phone);

            $PhoneNumber = implode(",",$phone);

            $SignName    = "易宝到家";          //模板签名

            $TemplateCode= $sms_code;         //模板CODE

            //阿里云模板里面的变量
            $TemplateParam = "";

            $send = Aliyunsms::sendSms(strval($PhoneNumber), $SignName, $TemplateCode, $TemplateParam);

            if ($send->Code == 'OK') {
                return $this->response()->success('操作成功')->refresh();
            } else {
                return $this->response()->error('短信发送失败，请检测短信模板')->refresh();
            }

        } catch (Exception $e) {
            return $this->response()->error('产生错误：'.$e->getMessage());
        }

    }

    public function form()
    {
        $this->select('sms_code', '短信模板')->options(SmsModel::selectOptions())->rules('required');

    }

    public function html()
    {
        return "<a class='remind btn btn-sm btn-warning' style='margin-left: 5px;'><i class='fa fa-info-circle'></i>&nbsp;提醒使用</a>";
    }

}
